#!/bin/bash

conf_ksf_item_array=("_agentka.ksf" "_agentkb.ksf")
conf_kms_item_array=("kmsagent.conf" "kmsconf.ksf" "backup_kmsconf.ksf")
function BackupKmsagentRelatedFile() {
    if [ ! -d ${kmsagent_work_path}/backup_data ]; then
        mkdir -p ${kmsagent_work_path}/backup_data
        if [ $? -ne 0 ]; then
            return 1
        fi
    fi

    chown -h ${username}:${usergroup} ${kmsagent_work_path}/backup_data
    su - ${username} -s /bin/bash -c "chmod 700 ${kmsagent_work_path}/backup_data" >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "[WARNING] Unable to configure backup data dir."
    fi

    for kms_item in "${conf_kms_item_array[@]}"; do
        if [ -f ${kmsagent_work_path}/${kms_item} ]; then
            if [ -L ${kmsagent_work_path}/${kms_item} ]; then
                echo "[WARNING] ${kmsagent_work_path##*/}/${kms_item} cannot be a soft link."
                return 1
            fi

            rm -f ${kmsagent_work_path}/backup_data/${kms_item} >/dev/null 2>&1
            cp -npf ${kmsagent_work_path}/${kms_item} ${kmsagent_work_path}/backup_data/ >/dev/null 2>&1
        fi
    done

    for ksf_item in "${conf_ksf_item_array[@]}"; do
        if [ -L ${kmsagent_work_path}/data/${username}${ksf_item} ]; then
            echo "[WARNING] ${kmsagent_work_path##*/}/data/${username}${ksf_item} cannot be a soft link."
            return 1
        fi

        rm -f ${kmsagent_work_path}/backup_data/${username}${ksf_item} >/dev/null 2>&1
        cp -npf ${kmsagent_work_path}/data/${username}${ksf_item} ${kmsagent_work_path}/backup_data/ >/dev/null 2>&1
    done
}

function CheckInputParamInvalid() {
    if [ ! -d ${kmsagent_work_path} ]; then
        echo "[WARNING] The kmsagent work path does not exist. No need to back up."
        return 1
    fi

    if [[ -z ${username} || -z ${usergroup} ]]; then
        echo "[WARNING] username/usergroup is invalid."
        return 1
    fi
}

function usage() {
    echo "Usage:"
    echo "     kmsagent_backup_conf.sh [kmsagent_work_path] [username] [usergroup]"
    exit -1
}

if [ $# -ne 3 ]; then
    echo "Incorrect number of parameters."
    usage
fi

kmsagent_work_path=$1
username=$2
usergroup=$3

CheckInputParamInvalid
if [ $? -ne 0 ];then
    exit -1
fi
BackupKmsagentRelatedFile
